import * as vscode from 'vscode'
import * as fs from 'fs'
import * as path from 'path'

export interface FunctionConfig {
    id: string
    title: string
    fun?: (context: string) => any
    command?: string
    description?: string
}

export class DynamicFunctionManager {
    private fileWatcher: vscode.FileSystemWatcher | undefined
    private functions: FunctionConfig[] = []

    constructor(private context: vscode.ExtensionContext) {
        this.init()
    }

    private init(): void {
        // 加载函数配置
        this.loadFunctions()

        // 监听配置文件变化
        this.watchConfigFile()
    }

    private loadFunctions(): void {
        const funConfigPath = path.join(vscode.workspace.rootPath || '', 'fun.js')

        // 默认函数配置
        const defaultFunctions: FunctionConfig[] = [
            {
                id: 'trimBrackets',
                title: '【替换】移除选中内容中的方括号',
                fun: function (context: string) {
                    return context.replace(/[\[\]]/g, '')
                },
                description: '替换选中数据',
            },
            {
                id: 'stringToArray',
                title: '0-待采购 1-采购中 转数组',
                fun: function (context) {
                    let arr = context.split(' ')
                    let res = arr.map((item) => {
                        let itemArr = item.split('-')
                        return {
                            label: itemArr[0],
                            value: itemArr[1],
                        }
                    })
                    return JSON.stringify(res)
                },
                description: "0-待采购 1-采购中 转[{label:'待采购',value:'0'},{label:'采购中',value:'1'}]",
            },
        ]

        if (!fs.existsSync(funConfigPath)) {
            this.functions = defaultFunctions
            return
        }

        try {
            // 删除缓存以确保加载最新版本
            delete require.cache[require.resolve(funConfigPath)]

            // 加载模块
            const config = require(funConfigPath)

            // 支持 export default [] 格式
            if (Array.isArray(config)) {
                this.functions = config
            } else if (config.default && Array.isArray(config.default)) {
                this.functions = config.default
            } else {
                this.functions = defaultFunctions
            }
        } catch (error) {
            vscode.window.showErrorMessage(`加载 fun.js 失败: ${error}`)
            this.functions = defaultFunctions
        }
    }

    private watchConfigFile(): void {
        this.fileWatcher = vscode.workspace.createFileSystemWatcher(
            new vscode.RelativePattern(vscode.workspace.rootPath || '', 'fun.js')
        )

        this.fileWatcher.onDidChange(() => {
            this.loadFunctions()
            vscode.window.showInformationMessage('KeyReplacer: 功能配置已更新')
        })

        this.fileWatcher.onDidCreate(() => {
            this.loadFunctions()
            vscode.window.showInformationMessage('KeyReplacer: 检测到新的功能配置')
        })

        this.fileWatcher.onDidDelete(() => {
            this.loadFunctions()
            vscode.window.showInformationMessage('KeyReplacer: 功能配置已删除，使用默认配置')
        })

        this.context.subscriptions.push(this.fileWatcher)
    }

    public async showFunctionMenu(): Promise<void> {
        if (this.functions.length === 0) {
            vscode.window.showInformationMessage('没有可用的功能')
            return
        }

        const items: vscode.QuickPickItem[] = this.functions.map((func) => ({
            label: func.title,
            description: func.description || '',
            detail: func.id,
        }))

        const selected = await vscode.window.showQuickPick(items, {
            placeHolder: '选择要执行的功能',
            matchOnDetail: true,
        })

        if (selected && selected.detail) {
            const functionConfig = this.functions.find((f) => f.id === selected.detail)
            if (functionConfig) {
                await this.executeFunction(functionConfig)
            }
        }
    }

    private async executeFunction(func: FunctionConfig): Promise<void> {
        const editor = vscode.window.activeTextEditor
        if (!editor) {
            vscode.window.showErrorMessage('没有活动的编辑器')
            return
        }

        const selection = editor.selection
        if (selection.isEmpty) {
            vscode.window.showErrorMessage('请先选择要处理的文本')
            return
        }

        const selectedText = editor.document.getText(selection)

        try {
            if (func.fun) {
                // 执行自定义函数
                const result = func.fun(selectedText)
                if (result !== undefined) {
                    // 替换选中文本
                    const edit = new vscode.WorkspaceEdit()
                    edit.replace(editor.document.uri, selection, String(result))
                    await vscode.workspace.applyEdit(edit)
                    vscode.window.showInformationMessage(`功能 "${func.title}" 执行完成`)
                }
            } else if (func.command) {
                // 执行预定义命令
                vscode.commands.executeCommand(func.command)
            } else {
                vscode.window.showErrorMessage(`功能 "${func.title}" 配置不完整`)
            }
        } catch (error) {
            vscode.window.showErrorMessage(`执行功能 "${func.title}" 失败: ${error}`)
        }
    }

    public getFunctions(): FunctionConfig[] {
        return this.functions
    }

    public dispose(): void {
        if (this.fileWatcher) {
            this.fileWatcher.dispose()
        }
    }
}
